package com.eoner.baselibrary.utils;

import android.net.Uri;
import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @auther hjian
 * @date 2020/5/29.
 */
public class StringsUtils {
    /*
    ** string 防止返回null
     */
    public static String toString(String str){
        return str == null?"":str;
    }

    //分享链接 拼接数据  埋点Sharecommondialog使用
    public static String urlAddParameters(String url, Map<String, String> param){
        try {
        url = url+(TextUtils.isEmpty(Uri.parse(url).getEncodedQuery())?"?":"&");
        for(Map.Entry<String, String> entry : param.entrySet()){
            if (!TextUtils.isEmpty(entry.getValue()))
            url += entry.getKey()+"="+ entry.getValue() +"&";
        }
        return url.substring(0,url.length()-1);
//        return url;
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return url;
    }

    static DecimalFormat df=new DecimalFormat("#0.00");
    public static boolean isPhoneNum(String phoneNum){
        if(!TextUtils.isEmpty(phoneNum)&&phoneNum.startsWith("1")&&phoneNum.length() == 11){
            return true;
        }else {
            return false;
        }
//        return  Pattern.matches("^1[3|4|5|6|7|8|9]{1}[0-9]{9}$",phoneNum);
    }

    public static String keep2num(String num){
        return df.format(Double.valueOf(num));
    }


    /**
     * @param str
     * @return
     * @Description: 32位小写MD5
     */
    public static String parseStrToMd5L32(String str){
        String reStr = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(str.getBytes());
            StringBuffer stringBuffer = new StringBuffer();
            for (byte b : bytes){
                int bt = b&0xff;
                if (bt < 16){
                    stringBuffer.append(0);
                }
                stringBuffer.append(Integer.toHexString(bt));
            }
            reStr = stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return reStr;
    }

    /**
     * @param str
     * @return
     * @Description: 32位大写MD5
     */
    public static String parseStrToMd5U32(String str){
        String reStr = parseStrToMd5L32(str);
        if (reStr != null){
            reStr = reStr.toUpperCase();
        }
        return reStr;
    }
}
